﻿namespace MinesweeperGame
{
    using System;
    using System.Text;

    public class Highscore
    {
        private readonly int maxHighscoresCount;
        private int[] openedCellsCount;
        private string[] playerName;
        private int highscoresCount;

        public Highscore(int maxHighscoresCount)
        {
            this.maxHighscoresCount = maxHighscoresCount;
            this.highscoresCount = -1;
            this.openedCellsCount = new int[maxHighscoresCount];
            this.playerName = new string[maxHighscoresCount];
        }

        public string DisplayHighscores()
        {
            StringBuilder highscoreString = new StringBuilder();
            highscoreString.AppendLine("Scoreboard:");

            int len;
            if (this.highscoresCount + 1 < this.maxHighscoresCount)
            {
                len = this.highscoresCount + 1;
            }
            else
            {
                len = this.maxHighscoresCount;
            }

            for (int i = 0; i < len; i++)
            {
                highscoreString.AppendFormat("{0}. {1} --> {2} cells", i + 1, this.playerName[i], this.openedCellsCount[i]);
                highscoreString.AppendLine("");
            }

            highscoreString.AppendLine("");
            return highscoreString.ToString();
        }



        public void SaveHighscore(int openCellsCount, string playerName)
        {
            if (this.highscoresCount < this.maxHighscoresCount - 1) 
            {
                this.highscoresCount++;
            }

            this.playerName[this.highscoresCount] = playerName;
            this.openedCellsCount[this.highscoresCount] = openCellsCount;
            
            // Sort new highscore result
            for (int i = 0; i < this.highscoresCount; i++)
            {
                for (int j = i + 1; j <= this.highscoresCount; j++)
                {
                    if (this.openedCellsCount[i] < this.openedCellsCount[j])
                    {
                        int exchangeValue = this.openedCellsCount[i];
                        this.openedCellsCount[i] = this.openedCellsCount[j];
                        this.openedCellsCount[j] = exchangeValue;

                        string exchangeName = this.playerName[i];
                        this.playerName[i] = this.playerName[j];
                        this.playerName[j] = exchangeName;
                    }
                }
            }
        }

        internal bool NewHighscore(int openCellsCount)
        {
            if (this.highscoresCount < (this.maxHighscoresCount - 1))
            {
                return true;
            }
            else if (this.openedCellsCount[this.highscoresCount] < openCellsCount)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
